using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using IntellisenseControl;
using ODT.Common.Core;
using ODT.Common.Services;
using ODT.GlobalMessageProcessor;
using ODT.Licensing;
using ODT.PMACGlobal;
using ODT.PowerPmacComLib;
using ODT.PPMACDatabase;
using PopupControl;
using PPTerminalControl.Properties;

namespace PPTerminalControl
{
	[LicenseProvider(typeof(ReflectingLicenseProvider))]
	[ToolboxBitmap("PPTerminalControl.bmp")]
	public class PPTerminalControl : UserControl, IDeviceConnectionControl
	{
		public delegate void PPTerminalDisplay(object sender, TerminalControlArg e);

		public class TerminalControlArg : EventArgs
		{
			private readonly string displayType;

			private readonly string deviceID;

			public string DisplayType => displayType;

			public string DeviceID => deviceID;

			public TerminalControlArg(string displayType, string deviceID)
			{
				this.displayType = displayType;
				this.deviceID = deviceID;
			}
		}

		public delegate void PPTerminalGlobalEvent(object sender, PPMACGlobalEventArgs e);

		public class PPMACGlobalEventArgs : EventArgs
		{
			private readonly string DeviceID;

			private readonly string Action;

			public string DEVICEID => DeviceID;

			public string ACTION => Action;

			public PPMACGlobalEventArgs(string device, string action)
			{
				DeviceID = device;
				Action = action;
			}
		}

		public delegate void PPTerminalLogMessage(object sender, TerminalLogArg e);

		public class TerminalLogArg : EventArgs
		{
			private string controltype;

			private string message;

			private string ipaddress;

			public string ControlType => controltype;

			public string Message => message;

			public string IpADDRESS => ipaddress;

			internal TerminalLogArg(string controltype, string message, string ipaddress)
			{
				this.controltype = controltype;
				this.message = message;
				this.ipaddress = ipaddress;
			}
		}

		public delegate void PPTerminalText(object sender, TerminalTextArg e);

		public class TerminalTextArg : EventArgs
		{
			private readonly string displayText;

			public string DisplayText => displayText;

			public TerminalTextArg(string displaytext)
			{
				displayText = displaytext;
			}
		}

		internal delegate void UserInterfaceDataEventHandler(string action, string formText);

		private delegate void AccessFormMarshalDelegate(string action, string textToAdd);

		private delegate void HandleIPChangeGlobalEventDelegate(string oldipAddr, string newipAddr, string action, ManualResetEvent InvokeComplete);

		private delegate void HandleGlobalEventDelegate(string ipAddr, string action, ManualResetEvent InvokeComplete);

		private IAsyncGpasciiCommunicationInterface AsyncGpasciiClient;

		private ISyncGpasciiCommunicationInterface SyncGpasciiClient;

		private IAmbientControl IambientCtrl = new AmbientProperties();

		private ITerminalControl IterminalCtrl = new ControlProperties();

		private Form ambientPropertyPage;

		private Form controlPropertyPage;

		private ManualResetEvent GpAsciiCallBack = new ManualResetEvent(false);

		private Popup intellisesnepopup;

		private Intellisense _intellisesnectrl;

		private PPDBUtilFunctions myDBUtilFunctions = new PPDBUtilFunctions();

		private Color cmdbgColor;

		private Color cmdfgColor;

		private Color rspbgColor;

		private Color rspMessageColor;

		private Color rspTypedColor;

		private Color rspNormalColor;

		private Color rspErrorColor;

		private Font txtFont;

		private int numCommands;

		private int maxLines;

		private int cmdIndex;

		private int SocketBuffer;

		private string[] CommandList = new string[Settings.Default.defMaxCommands * 2];

		private int globalcmdcount;

		private static int totalnoofwindows = 0;

		private int windowIDNumber;

		private const string gpasciiCmd = "gpascii";

		private const string gpasciiTerminated = "Terminated";

		private string unWantedResponse = "Open for MACRO COM\r\n";

		private int echoMode;

		private int lastEchoMode;

		private string Listboxselectedtext = string.Empty;

		private static string TypedChar = string.Empty;

		private static string InputString = string.Empty;

		private string oldstring = string.Empty;

		private bool backspace;

		private char deletedChar;

		private const int NUMLock_OemPeriod = 110;

		private bool bResetInProgress;

		private bool bLocalReset;

		private bool bLocalReboot;

		private bool bLoginSuccess;

		private bool bInMACROASCIIMode;

		private bool bCheckHeartbeat = true;

		private bool bShowResponseTime;

		private const char ESC = '\u001b';

		private string ACK = Convert.ToString('\u0006');

		private bool isTextBoxToBeClearedOnNextTextChange;

		private MessageSenderClass ResetActiveMessageSender = new MessageSenderClass(MessageSenderClass.SyncType.GlobalResetActive);

		private MessageSenderClass ResetCompleteMessageSender = new MessageSenderClass(MessageSenderClass.SyncType.GlobalResetComplete);

		private MessageSenderClass DisconnecteMessageSender = new MessageSenderClass(MessageSenderClass.SyncType.GlobalDisconnect);

		private MessageSenderClass RebootCompleteMessageSender = new MessageSenderClass(MessageSenderClass.SyncType.GlobalRebootComplete);

		private MessageReceiverClass DatabaseReloadEventReceiverClass = new MessageReceiverClass(MessageReceiverClass.SyncType.GlobalDatabaseSync);

		private MessageSenderClass SaveCompleteMessageSender = new MessageSenderClass(MessageSenderClass.SyncType.GlobalSaveComplete);

		private deviceProperties currentAddress = new deviceProperties();

		private deviceProperties previousAddress = new deviceProperties();

		private string welcomeText;

		private string selectDeviceText;

		private string windowTitle;

		private string ambientPropertiesText;

		private string applyText;

		private string controlPropertiesText;

		private string redefineCommandListText;

		private string commandListChangedText;

		private string communicationToDeviceSuccessfulFormat;

		private string communicationToDeviceFailedFormat;

		private string disconnectDeviceFormat;

		private string title;

		private string offlineText;

		private string onlineText;

		private string communicatingMacroStationFormat;

		private string timeOutFormat;

		private string sendingNotificationToStopCommunicationText;

		private string rebootingDeviceText;

		private string resettingDeviceText;

		private string deviceResetCompleteText;

		private string deviceResetFailedText;

		private string establishCommunicationToDeviceText;

		private string resetInProgressText;

		private string invalidCommandText;

		private string defaultFileNameText;

		private string saveFileNameTitle;

		private string resettingCommunicationCommandText;

		private string killAllMotorsCommandText;

		private string responseCommandTimeFormat;

		private string responseCommandTimedOutFormat;

		private string connectionDisconnectedText;

		private string macroStationExceptionFormat;

		private string terminalExceptionFormat;

		private string displayLabel;

		private string productNameText;

		private string saveInProgresText;

		private IContainer components;

		private ContextMenuStrip contextMenuStrip1;

		private ToolStripMenuItem propertiesToolStripMenuItem;

		private ToolStripMenuItem ambientToolStripMenuItem;

		private ToolStripMenuItem deviceToolStripMenuItem;

		private ToolStripMenuItem controlToolStripMenuItem;

		private ToolStripMenuItem clearBufferToolStripMenuItem;

		private ToolStripMenuItem copyBufferToFileToolStripMenuItem;

		private ToolStripMenuItem printBufferToolStripMenuItem;

		private ToolStripMenuItem setTerminalBufferToolStripMenuItem;

		private SplitContainer splitContainer1;

		private RichTextBox ResponseBox;

		private ToolStripSeparator toolStripSeparator1;

		private ToolStripMenuItem copyBufferToClipboardToolStripMenuItem;

		private RichTextBox richTextBox1;

		public event PPTerminalDisplay displayTerminalTitleChange;

		public event PPTerminalGlobalEvent PPMACGlobalEventAvailable;

		public event PPTerminalLogMessage TerminalLogMessageAvailable;

		public event PPTerminalText displayTerminalTextChange;

		internal static event UserInterfaceDataEventHandler UserInterfaceData;

		public PPTerminalControl()
		{
			ILanguageTranslationService service = ServiceManager.GetService<ILanguageTranslationService>();
			AsyncGpasciiClient = new AsyncDTCommunication();
			Thread.CurrentThread.CurrentCulture = IDEGlobals.USEnglishCulture;
			Thread.CurrentThread.CurrentUICulture = IDEGlobals.USEnglishCulture;
			InitializeComponent();
			SetLanguageTranslations(service);
			Control.CheckForIllegalCrossThreadCalls = false;
			totalnoofwindows++;
			cmdbgColor = Settings.Default.defcmdbgColor;
			cmdfgColor = Settings.Default.defcmdfgColor;
			rspbgColor = Settings.Default.defrspbgColor;
			rspMessageColor = Settings.Default.defrspMessageColor;
			rspTypedColor = Settings.Default.defrspTypedColor;
			rspNormalColor = Settings.Default.defrspNormalColor;
			rspErrorColor = Settings.Default.defrspErrorColor;
			txtFont = Settings.Default.defFont;
			ResponseBox.BackColor = rspbgColor;
			ResponseBox.ForeColor = rspMessageColor;
			ResponseBox.Font = txtFont;
			richTextBox1.BackColor = cmdbgColor;
			richTextBox1.ForeColor = cmdfgColor;
			richTextBox1.Font = txtFont;
			echoMode = Settings.Default.defechoMode;
			numCommands = Settings.Default.defMaxCommands;
			SocketBuffer = Settings.Default.defSocketBuffer;
			maxLines = Settings.Default.defMaxLines;
			ResponseBox.Clear();
			currentAddress.SetProperties(DeviceConnectionSettings.DefaultSettings);
            intellisesnepopup = new Popup(_intellisesnectrl = new Intellisense(service));
            intellisesnepopup.AutoClose = false;
            intellisesnepopup.FocusOnOpen = false;
            intellisesnepopup.Resizable = true;
            intellisesnepopup.ShowingAnimation = (intellisesnepopup.HidingAnimation = PopupAnimations.TopToBottom | PopupAnimations.Blend);
            _intellisesnectrl.SelectedText += _intellisesnectrl_SelectedText;
            _intellisesnectrl.SendKeyUp += _intellisesnectrl_SendKeyUp;
            _intellisesnectrl.LogIntellisenseMessage += _intellisesnectrl_LogIntellisenseMessage;
            richTextBox1.AllowDrop = true;
			richTextBox1.EnableAutoDragDrop = true;
			richTextBox1.DragEnter += RichTextBox1DragEnterOrOver;
			richTextBox1.DragOver += RichTextBox1DragEnterOrOver;
			richTextBox1.DragDrop += RichTextBox1DragDrop;
		}

		private void SetLanguageTranslations(ILanguageTranslationService languageTranslationService)
		{
			welcomeText = languageTranslationService.Translate("Terminal.WelcomeText");
			selectDeviceText = languageTranslationService.Translate("Common.SelectDeviceText");
			windowTitle = languageTranslationService.Translate("Terminal.WindowTitle");
			ambientPropertiesText = languageTranslationService.Translate("Common.AmbientProperties");
			applyText = languageTranslationService.Translate("Common.Apply");
			controlPropertiesText = languageTranslationService.Translate("Common.ControlProperties");
			redefineCommandListText = languageTranslationService.Translate("Terminal.RedefineCommandListText");
			commandListChangedText = languageTranslationService.Translate("Terminal.CommandListChanged");
			communicationToDeviceSuccessfulFormat = languageTranslationService.Translate("Common.CommunicationToDeviceSuccessfulFormat");
			communicationToDeviceFailedFormat = languageTranslationService.Translate("Common.CommunicationToDeviceFailedFormat");
			disconnectDeviceFormat = languageTranslationService.Translate("Common.DisconnectDeviceFormat");
			title = languageTranslationService.Translate("Terminal.Title");
			offlineText = languageTranslationService.Translate("Common.Offline");
			onlineText = languageTranslationService.Translate("Common.Online");
			communicatingMacroStationFormat = languageTranslationService.Translate("Terminal.CommunicatingMacroStationFormat");
			timeOutFormat = languageTranslationService.Translate("Common.TimeOutFormat");
			sendingNotificationToStopCommunicationText = languageTranslationService.Translate("Terminal.SendingNotificationToStopCommunicationText");
			rebootingDeviceText = languageTranslationService.Translate("Terminal.RebootingDeviceText");
			resettingDeviceText = languageTranslationService.Translate("Terminal.ResettingDeviceText");
			deviceResetCompleteText = languageTranslationService.Translate("Terminal.DeviceResetCompleteText");
			deviceResetFailedText = languageTranslationService.Translate("Terminal.DeviceResetFailedText");
			establishCommunicationToDeviceText = languageTranslationService.Translate("Common.EstablishCommunicationToDeviceText");
			resetInProgressText = languageTranslationService.Translate("Terminal.ResetInProgressText");
			invalidCommandText = languageTranslationService.Translate("Terminal.InvalidCommandText");
			defaultFileNameText = languageTranslationService.Translate("Terminal.DefaultFileNameText");
			saveFileNameTitle = languageTranslationService.Translate("Terminal.SaveFileNameTitle");
			resettingCommunicationCommandText = languageTranslationService.Translate("Terminal.ResettingCommunicationCommandText");
			killAllMotorsCommandText = languageTranslationService.Translate("Terminal.KillAllMotorsCommandText");
			responseCommandTimeFormat = languageTranslationService.Translate("Terminal.ResponseCommandTimeFormat");
			responseCommandTimedOutFormat = languageTranslationService.Translate("Terminal.ResponseCommandTimedOutFormat");
			connectionDisconnectedText = languageTranslationService.Translate("Terminal.ConnectionDisconnectedText");
			macroStationExceptionFormat = languageTranslationService.Translate("Terminal.MacroStationExceptionFormat");
			terminalExceptionFormat = languageTranslationService.Translate("Terminal.TerminalExceptionFormat");
			productNameText = languageTranslationService.Translate("Common.ProductName");
			saveInProgresText = languageTranslationService.Translate("Terminal.SaveInProgressText");
			SuspendLayout();
			propertiesToolStripMenuItem.Text = languageTranslationService.Translate("Common.Properties");
			ambientToolStripMenuItem.Text = languageTranslationService.Translate("Common.Ambient");
			controlToolStripMenuItem.Text = languageTranslationService.Translate("Common.Control");
			setTerminalBufferToolStripMenuItem.Text = languageTranslationService.Translate("Terminal.General");
			clearBufferToolStripMenuItem.Text = languageTranslationService.Translate("Terminal.ClearBuffer");
			copyBufferToFileToolStripMenuItem.Text = languageTranslationService.Translate("Terminal.SaveBuffer");
			printBufferToolStripMenuItem.Text = languageTranslationService.Translate("Terminal.PrintBuffer");
			copyBufferToClipboardToolStripMenuItem.Text = languageTranslationService.Translate("Terminal.CopyBuffer");
			ResponseBox.Text = (terminalExceptionFormat = languageTranslationService.Translate("Terminal.ResponseDefaultText"));
			richTextBox1.TextChanged -= richTextBox1_TextChanged;
			richTextBox1.Text = string.Empty;
			richTextBox1.TextChanged += richTextBox1_TextChanged;
			ResumeLayout(false);
		}

		public string GetCmdBackgroundColor()
		{
			return new ColorConverter().ConvertToString(cmdbgColor);
		}

		public void SetCmdBackgroundColor(string newColor)
		{
			ColorConverter colorConverter = new ColorConverter();
			try
			{
				if (newColor != string.Empty)
				{
					object obj = colorConverter.ConvertFromString(newColor);
					cmdbgColor = (Color)obj;
				}
				else
				{
					cmdbgColor = Settings.Default.defcmdbgColor;
				}
			}
			catch (NullReferenceException)
			{
				cmdbgColor = Settings.Default.defcmdbgColor;
			}
			richTextBox1.BackColor = cmdbgColor;
			colorConverter = null;
		}

		public string GetCmdForegroundColor()
		{
			return new ColorConverter().ConvertToString(cmdfgColor);
		}

		public void SetCmdForegroundColor(string newColor)
		{
			ColorConverter colorConverter = new ColorConverter();
			try
			{
				if (newColor != string.Empty)
				{
					object obj = colorConverter.ConvertFromString(newColor);
					cmdfgColor = (Color)obj;
				}
				else
				{
					cmdfgColor = Settings.Default.defcmdfgColor;
				}
			}
			catch (NullReferenceException)
			{
				cmdfgColor = Settings.Default.defcmdfgColor;
			}
			richTextBox1.ForeColor = cmdfgColor;
			colorConverter = null;
		}

		public string GetRspBackgroundColor()
		{
			return new ColorConverter().ConvertToString(rspbgColor);
		}

		public void SetRspBackgroundColor(string newColor)
		{
			ColorConverter colorConverter = new ColorConverter();
			try
			{
				if (newColor != string.Empty)
				{
					object obj = colorConverter.ConvertFromString(newColor);
					rspbgColor = (Color)obj;
				}
				else
				{
					rspbgColor = Settings.Default.defrspbgColor;
				}
			}
			catch (NullReferenceException)
			{
				rspbgColor = Settings.Default.defrspbgColor;
			}
			ResponseBox.BackColor = rspbgColor;
			colorConverter = null;
		}

		public string GetRspMessageColor()
		{
			return new ColorConverter().ConvertToString(rspMessageColor);
		}

		public void SetRspMessageColor(string newColor)
		{
			ColorConverter colorConverter = new ColorConverter();
			try
			{
				if (newColor != string.Empty)
				{
					object obj = colorConverter.ConvertFromString(newColor);
					rspMessageColor = (Color)obj;
				}
				else
				{
					rspMessageColor = Settings.Default.defrspMessageColor;
				}
			}
			catch (NullReferenceException)
			{
				rspMessageColor = Settings.Default.defrspMessageColor;
			}
			colorConverter = null;
		}

		public string GetRspTypedColor()
		{
			return new ColorConverter().ConvertToString(rspTypedColor);
		}

		public void SetRspTypedColor(string newColor)
		{
			ColorConverter colorConverter = new ColorConverter();
			try
			{
				if (newColor != string.Empty)
				{
					object obj = colorConverter.ConvertFromString(newColor);
					rspTypedColor = (Color)obj;
				}
				else
				{
					rspTypedColor = Settings.Default.defrspTypedColor;
				}
			}
			catch (NullReferenceException)
			{
				rspTypedColor = Settings.Default.defrspTypedColor;
			}
			colorConverter = null;
		}

		public string GetRspNormalColor()
		{
			return new ColorConverter().ConvertToString(rspNormalColor);
		}

		public void SetRspNormalColor(string newColor)
		{
			ColorConverter colorConverter = new ColorConverter();
			try
			{
				if (newColor != string.Empty)
				{
					object obj = colorConverter.ConvertFromString(newColor);
					rspNormalColor = (Color)obj;
				}
				else
				{
					rspNormalColor = Settings.Default.defrspNormalColor;
				}
			}
			catch (NullReferenceException)
			{
				rspNormalColor = Settings.Default.defrspNormalColor;
			}
			colorConverter = null;
		}

		public string GetRspErrorColor()
		{
			return new ColorConverter().ConvertToString(rspErrorColor);
		}

		public void SetRspErrorColor(string newColor)
		{
			ColorConverter colorConverter = new ColorConverter();
			try
			{
				if (newColor != string.Empty)
				{
					object obj = colorConverter.ConvertFromString(newColor);
					rspErrorColor = (Color)obj;
				}
				else
				{
					rspErrorColor = Settings.Default.defrspErrorColor;
				}
			}
			catch (NullReferenceException)
			{
				rspErrorColor = Settings.Default.defrspErrorColor;
			}
			colorConverter = null;
		}

		public string GetCurrentFont()
		{
			return new FontConverter().ConvertToString(txtFont);
		}

		public void SetCurrentFont(string newFont)
		{
			FontConverter fontConverter = new FontConverter();
			try
			{
				if (newFont != string.Empty)
				{
					object obj = fontConverter.ConvertFromString(newFont);
					txtFont = (Font)obj;
				}
				else
				{
					txtFont = Settings.Default.defFont;
				}
			}
			catch (NullReferenceException)
			{
				txtFont = Settings.Default.defFont;
			}
			ResponseBox.Font = txtFont;
			richTextBox1.Font = txtFont;
			splitContainer1.SplitterDistance = splitContainer1.Height - Math.Max(txtFont.Height + 5, 22);
			richTextBox1.Height = Math.Max(22, txtFont.Height + 5);
			DisplayResponseWithNewLine(welcomeText, rspMessageColor);
			DisplayResponseWithNewLine(selectDeviceText, rspMessageColor);
			fontConverter = null;
		}

		public string GetTotalNoOfWindows()
		{
			return totalnoofwindows.ToString();
		}

		public int GetWindowIdNumber()
		{
			return windowIDNumber;
		}

		public void SetWindowIdNumebr(int number)
		{
			try
			{
				if (number.ToString() != string.Empty)
				{
					windowIDNumber = number;
				}
				else
				{
					windowIDNumber = 0;
				}
			}
			catch (NullReferenceException)
			{
				windowIDNumber = 0;
			}
		}

		public string GetEchoMode()
		{
			return echoMode.ToString();
		}

		public void SetEchoMode(string newVal)
		{
			try
			{
				if (newVal != string.Empty)
				{
					echoMode = Convert.ToInt32(newVal);
				}
				else
				{
					echoMode = Settings.Default.defechoMode;
				}
			}
			catch (NullReferenceException)
			{
				echoMode = Settings.Default.defechoMode;
			}
		}

		public string GetHeartBeatFlag()
		{
			return bCheckHeartbeat.ToString();
		}

		public void SetHeartBeatFlag(string HeartBeat)
		{
			try
			{
				if (HeartBeat != string.Empty && HeartBeat.Contains("False"))
				{
					bCheckHeartbeat = false;
				}
				else
				{
					bCheckHeartbeat = Settings.Default.defCheckHeartbeat;
				}
			}
			catch (Exception)
			{
				bCheckHeartbeat = Settings.Default.defCheckHeartbeat;
			}
		}

		public string GetShowResponseTime()
		{
			return bShowResponseTime.ToString();
		}

		public void SetShowResponseTime(string responseTime)
		{
			try
			{
				if (responseTime != string.Empty && responseTime.Contains("True"))
				{
					bShowResponseTime = true;
				}
				else
				{
					bShowResponseTime = Settings.Default.defShowResponseTime;
				}
			}
			catch (Exception)
			{
				bShowResponseTime = Settings.Default.defShowResponseTime;
			}
		}

		public string GetDosKeyCommands()
		{
			return numCommands.ToString();
		}

		public void SetDosKeyCommands(string cmds)
		{
			int num = numCommands;
			try
			{
				if (cmds != string.Empty)
				{
					numCommands = Convert.ToInt32(cmds);
				}
				else
				{
					numCommands = Settings.Default.defMaxCommands;
				}
			}
			catch (NullReferenceException)
			{
				numCommands = Settings.Default.defMaxCommands;
			}
			int numCommand = numCommands;
		}

		public string GetMaxBufferLength()
		{
			return maxLines.ToString();
		}

		public void SetMaxBufferLength(string textbuf)
		{
			try
			{
				if (textbuf != string.Empty)
				{
					maxLines = Convert.ToInt32(textbuf);
				}
				else
				{
					maxLines = Settings.Default.defMaxLines;
				}
			}
			catch (NullReferenceException)
			{
				maxLines = Settings.Default.defMaxLines;
			}
		}

		public string GetSpliterPosition()
		{
			return (splitContainer1.SplitterDistance * 100 / splitContainer1.Height).ToString();
		}

		public void SetSpliterPosition(string number)
		{
		}

		public string GetSocketBufferSize()
		{
			return SocketBuffer.ToString();
		}

		public void SetSocketBufferSize(string sockbuf)
		{
			int socketBuffer = SocketBuffer;
			try
			{
				if (sockbuf != string.Empty)
				{
					SocketBuffer = Convert.ToInt32(sockbuf);
				}
				else
				{
					SocketBuffer = Settings.Default.defSocketBuffer;
				}
			}
			catch (NullReferenceException)
			{
				SocketBuffer = Settings.Default.defSocketBuffer;
			}
			int socketBuffer2 = SocketBuffer;
		}

		public void SetConnection(DeviceConnectionSettings connectionSettings)
		{
			previousAddress.SetProperties(currentAddress);
			currentAddress.SetProperties(connectionSettings);
		}

		public string GetIPAddress()
		{
			return currentAddress.IPAddress;
		}

		public void SetIPAddress(string IP)
		{
			try
			{
				if (IP != string.Empty)
				{
					previousAddress.IPAddress = currentAddress.IPAddress;
					currentAddress.IPAddress = IP;
				}
				else
				{
					currentAddress.IPAddress = DeviceConnectionSettings.DefaultSettings.IPAddress;
				}
			}
			catch (NullReferenceException)
			{
				currentAddress.IPAddress = DeviceConnectionSettings.DefaultSettings.IPAddress;
			}
		}

        public string GetlastConnectionStatus()
		{
			return bLoginSuccess.ToString();
		}

		public void AutoConnect()
		{
			ConnectDeviceCommunication(true);
		}

		public void ClosePopUpIntellisense()
		{
            if (intellisesnepopup.Visible)
            {
                intellisesnepopup.Close();
            }
        }

		private void DatabaseReloadEventReceiverClass_PPMACGlobalDatabaseSyncEvent(object sender, MessageReceiverClass.DataSyncMessageReceiverEvnetArgs e)
		{
			try
			{
				ManualResetEvent manualResetEvent = new ManualResetEvent(false);
				Invoke(new HandleGlobalEventDelegate(HandleGlobalEventHandler), e.ipAddress, "SYNCDATABASE", manualResetEvent);
				if (!manualResetEvent.WaitOne(4000, false))
				{
					LogErrorWithParams(timeOutFormat, "HandleGlobalEvent");
				}
			}
			catch (Exception ex)
			{
				SendLogMessage(ex.Message);
			}
		}

		public void HandleGlobalEventHandler(string ipAddress, string action)
		{
			if (action == "KILLALLMOTORS" && SendCommand("#*DKILL"))
			{
				string text = string.Format(killAllMotorsCommandText, currentAddress.IPAddress);
				SendLogMessage(text + Environment.NewLine);
				DisplayResponseWithNewLine(text, rspErrorColor);
			}
			if (!(currentAddress.IPAddress == ipAddress))
			{
				return;
			}
			switch (action)
			{
			case "BACKUPANDRESTORE":
				break;
			case "IPCHANGESTART":
				break;
			case "FIRMWARELOAD":
				break;
			case "SAVEACTIVE":
				break;
			case "SAVECOMPLETE":
				break;
			case "PHASEMOTOR":
				break;
			case "RESETACTIVE":
				bResetInProgress = true;
				break;
			case "RESETCOMPLETE":
				bResetInProgress = false;
				_intellisesnectrl.DataBase = currentAddress.IPAddress;
				_intellisesnectrl.ClearList();
				break;
			case "DISCONNECT":
				if (!bLocalReboot)
				{
					DisconnectDeviceCommunication();
				}
				break;
			case "REBOOTCOMPLETE":
				myDBUtilFunctions.ResetDataSyncFlag(currentAddress.IPAddress);
				ConnectDeviceCommunication(true);
				_intellisesnectrl.DataBase = currentAddress.IPAddress;
				_intellisesnectrl.ClearList();
				bLocalReboot = false;
				break;
			case "SYNCDATABASE":
				myDBUtilFunctions.ResetDataSyncFlag(currentAddress.IPAddress);
				_intellisesnectrl.DataBase = currentAddress.IPAddress;
				break;
			}
		}

		private void HandleGlobalEvent(string ipAddress, string action)
		{
			ManualResetEvent manualResetEvent = new ManualResetEvent(false);
			Invoke(new HandleGlobalEventDelegate(HandleGlobalEventHandler), ipAddress, action, manualResetEvent);
			if (!manualResetEvent.WaitOne(4000, false))
			{
				LogErrorWithParams(timeOutFormat, "HandleGlobalEvent");
			}
		}

		private void HandleGlobalEventHandler(string ipAddress, string action, ManualResetEvent InvokeComplete)
		{
			if (action == "KILLALLMOTORS" && SendCommand("#*DKILL"))
			{
				string text = string.Format(killAllMotorsCommandText, currentAddress.IPAddress);
				SendLogMessage(text + Environment.NewLine);
				DisplayResponseWithNewLine(text, rspErrorColor);
			}
			if (currentAddress.IPAddress == ipAddress)
			{
				switch (action)
				{
				case "RESETACTIVE":
					if (!bLocalReset)
					{
						DisconnectDeviceCommunication();
					}
					bResetInProgress = true;
					break;
				case "RESETCOMPLETE":
					if (!bLocalReset)
					{
						ConnectDeviceCommunication(true);
					}
					else
					{
						_intellisesnectrl.DataBase = currentAddress.IPAddress;
					}
					break;
				case "DISCONNECT":
					if (!bLocalReboot)
					{
						DisconnectDeviceCommunication();
					}
					break;
				case "REBOOTCOMPLETE":
					if (!bLocalReboot)
					{
						myDBUtilFunctions.ResetDataSyncFlag(currentAddress.IPAddress);
						ConnectDeviceCommunication(true);
						_intellisesnectrl.DataBase = currentAddress.IPAddress;
					}
					bLocalReboot = false;
					break;
				case "SYNCDATABASE":
					myDBUtilFunctions.ResetDataSyncFlag(currentAddress.IPAddress);
					_intellisesnectrl.DataBase = currentAddress.IPAddress;
					break;
				}
			}
			InvokeComplete.Set();
		}

		public void HandleIPChangeGlobalEvent(string oldipAddr, string newipAddr, string action)
		{
			ManualResetEvent manualResetEvent = new ManualResetEvent(false);
			Invoke(new HandleIPChangeGlobalEventDelegate(IPChangeGlobalEventHandler), oldipAddr, newipAddr, action, manualResetEvent);
			if (!manualResetEvent.WaitOne(4000, false))
			{
				LogErrorWithParams(timeOutFormat, "HandleIPChangeGlobalEvent");
			}
		}

		private void IPChangeGlobalEventHandler(string oldipAddr, string newipAddr, string action, ManualResetEvent InvokeComplete)
		{
			if (currentAddress.IPAddress == oldipAddr)
			{
				switch (action)
				{
				case "DISCONNECT":
				case "IPCHANGESTART":
					if (bLoginSuccess)
					{
						bResetInProgress = true;
						DisconnectDeviceCommunication();
					}
					break;
				case "REBOOTCOMPLETE":
					ConnectDeviceCommunication(true);
					break;
				case "IPCHANGECOMPLETE":
					currentAddress.IPAddress = newipAddr;
					previousAddress.IPAddress = newipAddr;
					ConnectDeviceCommunication(true);
					break;
				}
			}
			InvokeComplete.Set();
		}

		private void _intellisesnectrl_LogIntellisenseMessage(string text)
		{
			SendLogMessage(text);
		}

		private void RichTextBox1DragDrop(object sender, DragEventArgs e)
		{
			if (!e.Data.GetDataPresent(DataFormats.Text))
			{
				return;
			}
			string text = e.Data.GetData(DataFormats.Text) as string;
			if (text == null)
			{
				return;
			}
			string[] array = new Regex(Environment.NewLine, RegexOptions.IgnoreCase).Split(text);
			string[] array2 = array;
			foreach (string text2 in array2)
			{
				if (!HandleSpecialCommands(text2))
				{
					RearrangeCommands(text2);
					if (bShowResponseTime)
					{
						string response;
						ProcessSyncCommand(text2, out response);
						DisplayResponseWithNewLine(response, rspMessageColor);
					}
					else
					{
						ProcessCommand(text2);
					}
				}
			}
			if (array.Length != 0)
			{
				isTextBoxToBeClearedOnNextTextChange = true;
			}
			e.Effect = DragDropEffects.Copy;
		}

		private static void RichTextBox1DragEnterOrOver(object sender, DragEventArgs e)
		{
			e.Effect = (((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy && e.Data.GetDataPresent(DataFormats.Text)) ? DragDropEffects.Copy : DragDropEffects.None);
		}

		private void PPTerminalControl_Load(object sender, EventArgs e)
		{
			resetCursor();
			richTextBox1.Focus();
			UserInterfaceData += Control_UserInterfaceData;
			SetDisplayLabel();
			DatabaseReloadEventReceiverClass.PPMACGlobalDatabaseSyncEvent += DatabaseReloadEventReceiverClass_PPMACGlobalDatabaseSyncEvent;
		}

		private void PPTerminalAmbientMenu_Click(object sender, EventArgs e)
		{
			ambientPropertyPage = new Form();
			ambientPropertyPage.Icon = Resources.ApplicationIcon;
			ambientPropertyPage.ShowIcon = true;
			PropertyGrid propertyGrid = new PropertyGrid();
			AmbientProperties selectedObject = new AmbientProperties();
			Button button = new Button();
			ambientPropertyPage.FormClosed += ambientPropertyPage_FormClosed;
			ambientPropertyPage.Load += ambientPropertyPage_Load;
			ambientPropertyPage.Controls.Add(propertyGrid);
			ambientPropertyPage.Size = new Size(350, 320);
			ambientPropertyPage.MinimumSize = new Size(350, 320);
			ambientPropertyPage.MaximumSize = new Size(350, 320);
			ambientPropertyPage.MaximizeBox = false;
			ambientPropertyPage.MinimizeBox = false;
			propertyGrid.Size = new Size(320, 275);
			propertyGrid.Dock = DockStyle.Bottom;
			ambientPropertyPage.Text = $"{windowTitle} - {ambientPropertiesText}";
			propertyGrid.SelectedObject = selectedObject;
			ambientPropertyPage.StartPosition = FormStartPosition.CenterParent;
			ambientPropertyPage.Controls.Add(button);
			button.Text = applyText;
			button.AutoSize = true;
			button.Location = new Point(252, ambientPropertyPage.Top + 5);
			button.BringToFront();
			button.Click += AapplyChanges_Click;
			ambientPropertyPage.ShowDialog(IDEGlobals.CreateWin32WindowWrapperFromPtr(base.Handle));
			ambientPropertyPage.Dispose();
			ambientPropertyPage = null;
			propertyGrid.Dispose();
			propertyGrid = null;
			button.Dispose();
			button = null;
			selectedObject = null;
		}

		private void ambientPropertyPage_Load(object sender, EventArgs e)
		{
			IambientCtrl.CommandBackColor = cmdbgColor;
			IambientCtrl.CommandForeColor = cmdfgColor;
			IambientCtrl.ResponseBackColor = rspbgColor;
			IambientCtrl.SystemMessageColor = rspMessageColor;
			IambientCtrl.ResponseTypedColor = rspTypedColor;
			IambientCtrl.ResponseNormalColor = rspNormalColor;
			IambientCtrl.ResponseErrorColor = rspErrorColor;
			IambientCtrl.Font = txtFont;
		}

		private void AapplyChanges_Click(object sender, EventArgs e)
		{
			ApplyAmbientChanges();
		}

		private void ambientPropertyPage_FormClosed(object sender, EventArgs e)
		{
		}

		private void ApplyAmbientChanges()
		{
			cmdbgColor = IambientCtrl.CommandBackColor;
			cmdfgColor = IambientCtrl.CommandForeColor;
			rspbgColor = IambientCtrl.ResponseBackColor;
			rspMessageColor = IambientCtrl.SystemMessageColor;
			rspTypedColor = IambientCtrl.ResponseTypedColor;
			rspNormalColor = IambientCtrl.ResponseNormalColor;
			rspErrorColor = IambientCtrl.ResponseErrorColor;
			txtFont = IambientCtrl.Font;
			richTextBox1.BackColor = cmdbgColor;
			richTextBox1.ForeColor = cmdfgColor;
			richTextBox1.Font = txtFont;
			splitContainer1.SplitterDistance = splitContainer1.Height - Math.Max(txtFont.Height + 5, 22);
			richTextBox1.Height = Math.Max(22, txtFont.Height + 5);
			ResponseBox.BackColor = rspbgColor;
			ResponseBox.Font = txtFont;
		}

		private void setTerminalBufferToolStripMenuItem_Click(object sender, EventArgs e)
		{
			controlPropertyPage = new Form();
			controlPropertyPage.Icon = Resources.ApplicationIcon;
			controlPropertyPage.ShowIcon = true;
			PropertyGrid propertyGrid = new PropertyGrid();
			ControlProperties selectedObject = new ControlProperties();
			Button button = new Button();
			controlPropertyPage.FormClosed += controlPropertyPage_FormClosed;
			controlPropertyPage.Load += controlPropertyPage_Load;
			controlPropertyPage.Controls.Add(propertyGrid);
			controlPropertyPage.Size = new Size(350, 300);
			controlPropertyPage.MinimumSize = new Size(350, 300);
			controlPropertyPage.MaximumSize = new Size(350, 300);
			controlPropertyPage.MaximizeBox = false;
			controlPropertyPage.MinimizeBox = false;
			propertyGrid.Size = new Size(300, 250);
			propertyGrid.Dock = DockStyle.Bottom;
			controlPropertyPage.Text = $"{windowTitle} - {controlPropertiesText}";
			controlPropertyPage.Controls.Add(button);
			button.Text = applyText;
			button.AutoSize = true;
			button.Location = new Point(252, controlPropertyPage.Top + 7);
			button.BringToFront();
			button.Click += CapplyChanges_Click;
			propertyGrid.SelectedObject = selectedObject;
			controlPropertyPage.StartPosition = FormStartPosition.CenterParent;
			controlPropertyPage.ShowDialog(IDEGlobals.CreateWin32WindowWrapperFromPtr(base.Handle));
			controlPropertyPage.Dispose();
			controlPropertyPage = null;
			propertyGrid.Dispose();
			propertyGrid = null;
			button.Dispose();
			button = null;
			selectedObject = null;
		}

		private void CapplyChanges_Click(object sender, EventArgs e)
		{
			ApplyControlChanges();
			controlPropertyPage.Close();
		}

		private void ApplyControlChanges()
		{
			int num = numCommands;
			int num2 = echoMode;
			try
			{
				echoMode = IterminalCtrl.EchoMode;
				bShowResponseTime = IterminalCtrl.ShowResponseTime;
				maxLines = IterminalCtrl.TerminalBufferLines;
				num = IterminalCtrl.Commands;
			}
			catch (Exception)
			{
				echoMode = Settings.Default.defechoMode;
				num = Settings.Default.defMaxCommands;
				maxLines = Settings.Default.defMaxLines;
				bCheckHeartbeat = Settings.Default.defCheckHeartbeat;
				bShowResponseTime = Settings.Default.defShowResponseTime;
			}
			if (SyncGpasciiClient != null && SyncGpasciiClient.GpAsciiConnected && num2 != echoMode)
			{
				string response;
				ProcessSyncCommand("echo" + echoMode, out response);
			}
			if (numCommands != num)
			{
				MessageBox.Show(redefineCommandListText, commandListChangedText);
			}
		}

		private void controlPropertyPage_Load(object sender, EventArgs e)
		{
			IterminalCtrl.EchoMode = echoMode;
			IterminalCtrl.ShowResponseTime = bShowResponseTime;
			IterminalCtrl.TerminalBufferLines = maxLines;
			IterminalCtrl.Commands = numCommands;
		}

		private void controlPropertyPage_FormClosed(object sender, EventArgs e)
		{
		}

		private void PPTerminalControl_BackColorChanged(object sender, EventArgs e)
		{
			ResponseBox.BackColor = BackColor;
		}

		private void PPTerminalControl_FontChanged(object sender, EventArgs e)
		{
			ResponseBox.Font = Font;
		}

		private void PPTerminalControl_ForeColorChanged(object sender, EventArgs e)
		{
			ResponseBox.ForeColor = ForeColor;
		}

		private void PPTerminalControl_Click(object sender, EventArgs e)
		{
			resetCursor();
		}

		private void PPTerminalControl_MouseClick(object sender, MouseEventArgs e)
		{
			resetCursor();
		}

		private void LoadDeviceProperties(ref deviceProperties _destination, ref deviceProperties _source)
		{
			_destination.IPAddress = _source.IPAddress;
			_destination.Protocol = _source.Protocol;
			_destination.PortNumber = _source.PortNumber;
			_destination.User = _source.User;
			_destination.Password = _source.Password;
		}

		private bool ConnectDeviceCommunication(bool bShowMsg)
		{
			if (currentAddress.IPAddress.IsNoDevice)
			{
				if (bLoginSuccess)
				{
					DisconnectDeviceCommunication();
				}
				_intellisesnectrl.DataBase = currentAddress.IPAddress;
				_intellisesnectrl.ClearList();
				return false;
			}
			if (bLoginSuccess)
			{
				if (currentAddress.IPAddress == previousAddress.IPAddress && currentAddress.Protocol == previousAddress.Protocol)
				{
					return true;
				}
				DisconnectDeviceCommunication();
			}
			AsyncGpasciiClient = AsyncGpasciiClient ?? new AsyncDTCommunication();
			SyncGpasciiClient = SyncGpasciiClient ?? new DTCommunication();
			myDBUtilFunctions.DBUtilLogMessage += myDBUtilFunctions_DBUtilLogMessage;
			Cursor cursor = Cursor;
			Cursor = Cursors.WaitCursor;
			AsyncGpasciiClient.log += AsyncGpasciiClient_log;
			if (!AsyncGpasciiClient.ConnectGPAscii(currentAddress.IPAddress, currentAddress.PortNumber, currentAddress.User, currentAddress.Password))
			{
				AsyncGpasciiClient.DisconnectGpascii();
			}
			if (AsyncGpasciiClient.GpAsciiConnected)
			{
				AsyncGpasciiClient.ComERROR += AsyncGpasciiClient_ComERROR;
				AsyncGpasciiClient.AsyncDataAvailable += AsyncGpasciiClient_AsyncDataAvailable;
				bLoginSuccess = true;
				LoadDeviceProperties(ref previousAddress, ref currentAddress);
				SyncGpasciiClient.ConnectGpAscii(currentAddress.IPAddress, currentAddress.PortNumber, currentAddress.User, currentAddress.Password);
				DisplayResponseWithNewLine(string.Format(communicationToDeviceSuccessfulFormat, currentAddress.Protocol, currentAddress.IPAddress), rspMessageColor);
				if (SyncGpasciiClient.GpAsciiConnected)
				{
					string response;
					ProcessSyncCommand("echo" + echoMode, out response);
				}
				ProcessCommand("echo" + echoMode);
			}
			else if (bShowMsg)
			{
				DisplayResponseWithNewLine(string.Format(communicationToDeviceFailedFormat, currentAddress.IPAddress), rspMessageColor);
			}
			if (bLoginSuccess)
			{
				_intellisesnectrl.DataBase = currentAddress.IPAddress;
				bResetInProgress = false;
				bLocalReset = false;
				bLocalReboot = false;
			}
			SetDisplayLabel();
			Cursor = cursor;
			if (!richTextBox1.Focused)
			{
				richTextBox1.Focus();
				richTextBox1.Focus();
			}
			return bLoginSuccess;
		}

		private void CloseAndReOpenGpAscii()
		{
			DisconnectDeviceCommunication();
			ConnectDeviceCommunication(true);
		}

		private void myDBUtilFunctions_DBUtilLogMessage(object sender, PPDBUtilFunctions.DbUtilLogArg e)
		{
			SendLogMessage(e.Message);
		}

		private bool DisconnectDeviceCommunication()
		{
			if (AsyncGpasciiClient != null)
			{
				AsyncGpasciiClient.AsyncDataAvailable -= AsyncGpasciiClient_AsyncDataAvailable;
				if (AsyncGpasciiClient.GpAsciiConnected)
				{
					AsyncGpasciiClient.DisconnectGpascii();
					DisplayResponseWithNewLine(string.Format(disconnectDeviceFormat, previousAddress.IPAddress), rspMessageColor);
				}
				AsyncGpasciiClient.ComERROR -= AsyncGpasciiClient_ComERROR;
				AsyncGpasciiClient.log -= AsyncGpasciiClient_log;
			}
			if (SyncGpasciiClient != null && SyncGpasciiClient.GpAsciiConnected)
			{
				SyncGpasciiClient.DisconnectGpascii();
			}
			bLoginSuccess = false;
			SetDisplayLabel();
			return !bLoginSuccess;
		}

		private void SetDisplayLabel(int station = 0)
		{
			if (this.displayTerminalTitleChange != null)
			{
				string text = ((bLoginSuccess && bInMACROASCIIMode) ? string.Format(communicatingMacroStationFormat, station) : string.Empty);
				if (!string.Equals(displayLabel, $"{title} : {text}"))
				{
					this.displayTerminalTitleChange(this, new TerminalControlArg(title, text));
					displayLabel = $"{title} : {text}";
				}
			}
		}

		private void SendLogMessage(string message)
		{
			this.TerminalLogMessageAvailable?.Invoke(this, new TerminalLogArg(title, message, currentAddress.IPAddress));
		}

		private void LogErrorWithParams(string messageFormat, params object[] args)
		{
			this.TerminalLogMessageAvailable?.Invoke(this, new TerminalLogArg(title, string.Format(messageFormat, args), currentAddress.IPAddress));
		}

		private void SendGlobalEvent(string Action)
		{
			string iPAddress = currentAddress.IPAddress;
			switch (Action)
			{
			case "RESETACTIVE":
				ResetActiveMessageSender.IPAddress = iPAddress;
				ResetActiveMessageSender.SendSyncMessage();
				break;
			case "RESETCOMPLETE":
				ResetCompleteMessageSender.IPAddress = iPAddress;
				ResetCompleteMessageSender.SendSyncMessage();
				break;
			case "DISCONNECT":
				DisconnecteMessageSender.IPAddress = iPAddress;
				DisconnecteMessageSender.SendSyncMessage();
				break;
			case "REBOOTCOMPLETE":
				RebootCompleteMessageSender.IPAddress = iPAddress;
				RebootCompleteMessageSender.SendSyncMessage();
				break;
			case "SAVECOMPLETE":
				SaveCompleteMessageSender.IPAddress = iPAddress;
				SaveCompleteMessageSender.SendSyncMessage();
				break;
			}
		}

		public bool connectReconnectLogic()
		{
			if (bLoginSuccess)
			{
				if (currentAddress.IPAddress == previousAddress.IPAddress && currentAddress.Protocol == previousAddress.Protocol)
				{
					return true;
				}
				if (!currentAddress.IPAddress.IsNoDevice)
				{
					DisconnectDeviceCommunication();
					return ConnectDeviceCommunication(false);
				}
				DisconnectDeviceCommunication();
			}
			return ConnectDeviceCommunication(false);
		}

		private void RearrangeCommands(string command)
		{
			int num = -1;
			if (!(command != ""))
			{
				return;
			}
			if (globalcmdcount == numCommands)
			{
				globalcmdcount--;
			}
			for (int i = 0; i < globalcmdcount; i++)
			{
				if (CommandList[i].ToLower() == command.ToLower())
				{
					num = i;
					break;
				}
			}
			if (num >= 0)
			{
				for (int i = num - 1; i >= 0; i--)
				{
					CommandList[i + 1] = CommandList[i];
				}
				CommandList[0] = command.Trim();
				return;
			}
			for (int i = globalcmdcount - 1; i >= 0; i--)
			{
				CommandList[i + 1] = CommandList[i];
			}
			CommandList[0] = command.Trim();
			globalcmdcount++;
		}

		private void ProcessCommand(string command)
		{
			if (bLoginSuccess)
			{
				SendCommand(command);
			}
		}

		private bool ProcessSyncCommand(string command, out string response)
		{
			response = string.Empty;
			if (!bLoginSuccess)
			{
				return false;
			}
			Stopwatch stopwatch = new Stopwatch();
			if (SyncGpasciiClient != null && SyncGpasciiClient.GpAsciiConnected)
			{
				if (bShowResponseTime)
				{
					stopwatch.Start();
				}
				Status response2 = SyncGpasciiClient.GetResponse(command, out response);
				if (bShowResponseTime)
				{
					stopwatch.Stop();
					TimeSpan elapsed = stopwatch.Elapsed;
					DisplayResponse(response, rspNormalColor);
					DisplayResponseWithNewLine(string.Format(responseCommandTimeFormat, command, response.Length, elapsed.TotalSeconds), rspMessageColor);
				}
				switch (response2)
				{
				case Status.TimeOut:
					DisplayResponseWithNewLine(string.Format(responseCommandTimedOutFormat, command, response), rspErrorColor);
					return false;
				case Status.Ok:
					if (!response.ToLower().Contains("error"))
					{
						return true;
					}
					break;
				}
				return false;
			}
			return false;
		}

		private bool SendCommand(string command)
		{
			bool result = false;
			if (AsyncGpasciiClient != null && AsyncGpasciiClient.GpAsciiConnected && AsyncGpasciiClient.AsyncGetResponse(command, echoMode) == Status.Ok)
			{
				result = true;
			}
			return result;
		}

		private bool HandleSpecialCommands(string newCommand)
		{
			if (bLoginSuccess)
			{
				string empty = string.Empty;
				int num = -1;
				RearrangeCommands(newCommand.Trim());
				DisplayResponseWithNewLine(newCommand, rspTypedColor);
				string text = newCommand.ToLower();
				if (text.Contains("macrostation"))
				{
					if (text.Contains("macrostation") && text.Contains("close"))
					{
						bInMACROASCIIMode = false;
						ProcessCommand(newCommand);
						SetDisplayLabel();
						return true;
					}
					bInMACROASCIIMode = true;
					ProcessCommand(newCommand);
					try
					{
						string text2 = newCommand.Substring(12);
						if (!string.IsNullOrEmpty(text2))
						{
							num = Convert.ToInt32(text2.Trim());
						}
					}
					catch (Exception ex)
					{
						string text3 = string.Format(macroStationExceptionFormat, ex.Message);
						SendLogMessage(text3 + Environment.NewLine);
					}
					SetDisplayLabel(num);
					return true;
				}
				if (text.Length > 5 && text.Substring(0, 6).Contains("reboot"))
				{
					DisplayResponseWithNewLine(sendingNotificationToStopCommunicationText, rspMessageColor);
					string action = "DISCONNECT";
					bLocalReboot = true;
					bResetInProgress = true;
					DisplayResponseWithNewLine(rebootingDeviceText, rspMessageColor);
					ProcessCommand(text);
					SendGlobalEvent(action);
					return true;
				}
				if (!text.Contains("macroslave") && text.Length > 2 && text.Substring(0, 3).Contains("$$$"))
				{
					DisplayResponseWithNewLine(resettingDeviceText, rspMessageColor);
					string action = "RESETACTIVE";
					bLocalReset = true;
					bResetInProgress = true;
					SendGlobalEvent(action);
					if ((!text.Contains("**")) ? AsyncGpasciiClient.PowerPMACReset(ResetType.Reset) : AsyncGpasciiClient.PowerPMACReset(ResetType.FullReset))
					{
						DisplayResponseWithNewLine(deviceResetCompleteText, rspMessageColor);
					}
					else
					{
						DisplayResponseWithNewLine(deviceResetFailedText, rspErrorColor);
					}
					SendGlobalEvent("RESETCOMPLETE");
					bLocalReset = false;
					bResetInProgress = false;
					return true;
				}
				if (text.Length > 2 && (text == "save" || text == "sav"))
				{
					PowerPmacSave(text);
					return true;
				}
				return false;
			}
			DisplayResponseWithNewLine(establishCommunicationToDeviceText, rspMessageColor);
			return true;
		}

		private void AsyncGpasciiClient_AsyncDataAvailable(object sender, AsyncDataArgs e)
		{
			string empty2 = string.Empty;
			string empty3 = string.Empty;
			string empty = string.Empty;
			try
			{
				empty = e.Response;
				if (empty == string.Empty)
				{
					return;
				}
				if (empty.Contains("Terminated"))
				{
					DisconnectDeviceCommunication();
					return;
				}
				if (bLocalReboot && (empty.Contains("Shutting down Power PMAC Kernel") || empty.ToLower().Contains("reboot now") || empty.ToLower().Contains("restarting system")))
				{
					DisplayResponse(empty, rspErrorColor);
					empty = string.Empty;
					DisplayResponse(connectionDisconnectedText, rspMessageColor);
				}
				if (bResetInProgress)
				{
					if (empty.Contains("STDIN"))
					{
						if (bLocalReset)
						{
							SendGlobalEvent("RESETCOMPLETE");
							DisplayResponseWithNewLine(deviceResetCompleteText, rspMessageColor);
							bLocalReset = false;
							DisplayResponse(empty, rspNormalColor);
						}
						Cursor = Cursors.Default;
						bResetInProgress = false;
						GpAsciiCallBack.Set();
					}
					else if (empty.Contains("stdin:"))
					{
						if (bLocalReset)
						{
							DisplayResponseWithNewLine(invalidCommandText, rspErrorColor);
							SendGlobalEvent("RESETCOMPLETE");
							bLocalReset = false;
							bResetInProgress = false;
						}
					}
					else
					{
						string text3 = (string)currentAddress.IPAddress;
						DisplayResponse(empty, rspErrorColor);
					}
					SendLogMessage(empty);
					empty = string.Empty;
					return;
				}
				if (empty.Contains("STDIN"))
				{
					GpAsciiCallBack.Set();
					return;
				}
				if (empty.Contains(unWantedResponse))
				{
					empty = string.Empty;
					return;
				}
				string[] array = empty.Split('\u0006');
				int num = ((array.Length <= 1) ? array.Length : (array.Length - 1));
				for (int i = 0; i < num; i++)
				{
					if (!(array[i] != string.Empty))
					{
						continue;
					}
					string text = array[i];
					if (text.Contains("error #"))
					{
						string[] array2 = text.Split(new char[1] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
						foreach (string text2 in array2)
						{
							DisplayResponseWithNewLine(text2, text2.Contains("error #") ? rspErrorColor : rspNormalColor);
						}
					}
					else
					{
						DisplayResponse(text, rspNormalColor);
					}
				}
			}
			catch (Exception ex)
			{
				string message = string.Format(terminalExceptionFormat, ex.Message) + Environment.NewLine;
				SendLogMessage(message);
			}
		}

		private void AsyncGpasciiClient_log(object sender, LogArgs e)
		{
			SendLogMessage(e.LogMessage);
		}

		private void AsyncGpasciiClient_ComERROR(object sender, ComErArgs e)
		{
			if (AsyncGpasciiClient.GpAsciiConnected)
			{
				DisconnectDeviceCommunication();
			}
			if (PPTerminalControl.UserInterfaceData != null)
			{
				PPTerminalControl.UserInterfaceData("MessageBox", e.ErrorMessage);
			}
		}

		private void Control_UserInterfaceData(string action, string formText)
		{
			AccessFormMarshalDelegate method = ThreadSafeCall;
			object[] args = new object[2] { action, formText };
			Invoke(method, args);
		}

		private void ThreadSafeCall(string action, string formText)
		{
			if (action == "MessageBox")
			{
				SendLogMessage(formText);
			}
		}

		private void DisplayResponseWithNewLine(string text, Color newColor)
		{
			DisplayResponse(text + Environment.NewLine, newColor);
		}

		private void DisplayResponse(string text, Color newColor)
		{
			try
			{
				if (ResponseBox.Lines.Length > maxLines)
				{
					ResponseBox.Clear();
				}
				ResponseBox.SelectionStart = ResponseBox.Text.Length;
				ResponseBox.SelectionColor = newColor;
				ResponseBox.SelectedText += text;
				ResponseBox.ScrollToCaret();
				richTextBox1.Focus();
			}
			catch (Exception)
			{
			}
		}

		private void resetCursor()
		{
			richTextBox1.Focus();
			richTextBox1.Focus();
		}

		private void clearBufferToolStripMenuItem_Click(object sender, EventArgs e)
		{
			ResponseBox.Clear();
		}

		private void copyBufferToFileToolStripMenuItem_Click(object sender, EventArgs e)
		{
			SaveFileDialog saveFileDialog = new SaveFileDialog
			{
				FileName = defaultFileNameText,
				DefaultExt = ".txt",
				Filter = "Text files (*.txt)|*.txt",
				Title = saveFileNameTitle
			};
			if (saveFileDialog.ShowDialog(IDEGlobals.CreateWin32WindowWrapperFromPtr(base.Handle)) == DialogResult.OK && saveFileDialog.FileName.Length > 0)
			{
				ResponseBox.SaveFile(saveFileDialog.FileName, RichTextBoxStreamType.PlainText);
			}
			saveFileDialog.Dispose();
		}

		private void copyBufferToClipboardToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (ResponseBox.Text != "")
			{
				Clipboard.SetDataObject(ResponseBox.Text);
			}
		}

		private void printBufferToolStripMenuItem_Click(object sender, EventArgs e)
		{
			PrintDialog printDialog = new PrintDialog();
			PrintDocument printDocument = new PrintDocument();
			printDocument.PrintPage += documentToPrint_PrintPage;
			printDialog.Document = printDocument;
			if (printDialog.ShowDialog(IDEGlobals.CreateWin32WindowWrapperFromPtr(base.Handle)) == DialogResult.OK)
			{
				printDocument.Print();
			}
			printDocument.Dispose();
			printDocument = null;
			printDialog.Dispose();
		}

		private void documentToPrint_PrintPage(object sender, PrintPageEventArgs e)
		{
			float num = 0f;
			float num2 = 0f;
			int i = 0;
			float num3 = e.MarginBounds.Left;
			float num4 = e.MarginBounds.Top;
			string text = null;
			Font font = ResponseBox.Font;
			SolidBrush solidBrush = new SolidBrush(Color.Black);
			StringReader stringReader = new StringReader(ResponseBox.Text);
			for (num = (float)e.MarginBounds.Height / font.GetHeight(e.Graphics); (float)i < num; i++)
			{
				if ((text = stringReader.ReadLine()) == null)
				{
					break;
				}
				num2 = num4 + (float)i * font.GetHeight(e.Graphics);
				e.Graphics.DrawString(text, font, solidBrush, num3, num2, new StringFormat());
			}
			if (text != null)
			{
				e.HasMorePages = true;
			}
			else
			{
				e.HasMorePages = false;
			}
			solidBrush.Dispose();
			solidBrush = null;
			stringReader.Dispose();
			stringReader = null;
		}

		protected override bool ProcessCmdKey(ref Message msg, Keys KeyValue)
		{
			Convert.ToInt32(Keys.ControlKey | Keys.Control);
			switch (KeyValue)
			{
			case Keys.Tab:
				return true;
			case Keys.F1:
				return true;
			default:
                if (intellisesnepopup.Visible)
                {
                    if (KeyValue == Keys.Return || KeyValue == Keys.Up || KeyValue == Keys.Down || KeyValue == Keys.Escape)
                    {
                        KeyValue = Keys.None;
                        return true;
                    }
                }
                else
                {
					switch (KeyValue)
					{
					case Keys.Return:
					case Keys.Escape:
					case Keys.Up:
					case Keys.Down:
						KeyValue = Keys.None;
						return true;
					case Keys.C | Keys.Control:
						if (string.Empty == ResponseBox.SelectedText && string.Empty == richTextBox1.SelectedText)
						{
							KeyValue = Keys.None;
							DisplayResponseWithNewLine(resettingCommunicationCommandText, rspMessageColor);
							CloseAndReOpenGpAscii();
						}
						break;
					}
				}
				return base.ProcessCmdKey(ref msg, KeyValue);
			}
		}

		private void ResponseBox_Click(object sender, EventArgs e)
		{
		}

		private void ResponseBox_KeyDown(object sender, KeyEventArgs e)
		{
			if (!e.Control)
			{
				char c = Convert.ToChar(e.KeyValue);
				resetCursor();
				if (e.KeyCode != Keys.ShiftKey && e.KeyCode != Keys.Alt && e.KeyCode != Keys.ControlKey && e.KeyValue != 37 && e.KeyData != Keys.Right && e.KeyCode != Keys.Up && e.KeyCode != Keys.Down && e.KeyCode != Keys.Tab && e.KeyCode != Keys.Return && e.KeyCode != Keys.F1 && e.KeyCode != Keys.F2 && e.KeyCode != Keys.F3 && e.KeyCode != Keys.F4 && e.KeyCode != Keys.F5 && e.KeyCode != Keys.F6 && e.KeyCode != Keys.F7 && e.KeyCode != Keys.F8 && e.KeyCode != Keys.F9 && e.KeyCode != Keys.F10 && e.KeyCode != Keys.F11 && e.KeyCode != Keys.F12 && e.KeyValue > 31 && e.KeyValue < 128)
				{
					richTextBox1.Text += c;
				}
				richTextBox1.SelectionStart = richTextBox1.TextLength;
			}
		}

		private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Return)
			{
				e.SuppressKeyPress = true;
			}
			oldstring = richTextBox1.Text;
			backspace = e.KeyCode == Keys.Back;
			if (backspace && deletedChar.ToString().Equals("."))
			{
                _intellisesnectrl.ClearList();
                intellisesnepopup.Close();
            }
		}

		private void richTextBox1_TextChanged(object sender, EventArgs e)
		{
			if (isTextBoxToBeClearedOnNextTextChange)
			{
				richTextBox1.Clear();
				isTextBoxToBeClearedOnNextTextChange = false;
				return;
			}
			try
			{
				deletedChar = '\0';
				if (!backspace)
				{
					return;
				}
				string text = richTextBox1.Text;
				int num = Math.Min(richTextBox1.Text.Length, oldstring.Length);
				for (int i = 0; i < num; i++)
				{
					if (oldstring[i] != text[i])
					{
						deletedChar = oldstring[i];
						break;
					}
				}
				if (deletedChar == '\0' && oldstring.Length > 0)
				{
					deletedChar = oldstring[oldstring.Length - 1];
				}
				backspace = false;
			}
			catch (Exception ex)
			{
				SendLogMessage(ex.Message);
			}
		}

		private void _intellisesnectrl_SelectedText(string text)
		{
			Listboxselectedtext = text;
            _intellisesnectrl.ClearList();
            intellisesnepopup.Close();
            SetTextInRTBox(Listboxselectedtext);
			richTextBox1.Focus();
		}

		private void _intellisesnectrl_SendKeyUp(KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Escape || e.KeyCode == Keys.Back || e.KeyCode == Keys.Up)
			{
                intellisesnepopup.Close();
                _intellisesnectrl.ClearList();
                richTextBox1.SelectionStart = richTextBox1.Text.Length;
				richTextBox1.Focus();
			}
		}

		private int GetIndex()
		{
			string text = richTextBox1.Text;
			int num = GetCaretCoordinates(richTextBox1).Y;
			int num2 = 0;
			string text2 = "";
			int num3 = num;
			if (num3 >= 1)
			{
				string text3 = "";
				char c = '\0';
				while (num3 > 0 && text.Length > 0)
				{
					num3--;
					try
					{
						text3 = text.Substring(num3, 1);
					}
					catch (ArgumentOutOfRangeException)
					{
						text3 = string.Empty;
					}
					string text4 = text.ToLower();
					c = text3[0];
					if ((c.CompareTo('.') == 0 || c.CompareTo('=') == 0 || c.CompareTo('+') == 0 || c.CompareTo('-') == 0 || c.CompareTo('*') == 0 || c.CompareTo('/') == 0 || c.CompareTo(' ') == 0) && text4[0].CompareTo('j') != 0)
					{
						break;
					}
					text2 += c;
					num2++;
				}
				char[] array = text2.ToCharArray();
				Array.Reverse(array);
				text2 = new string(array);
			}
			return num - num2;
		}

		private void SetTextInRTBox(string text)
		{
			string obj = richTextBox1.Text;
			int num = 0;
			num = ((!obj.Trim().ToLower().Equals(text.ToLower())) ? GetIndex() : 0);
			if (num >= 0)
			{
				AppendTextToIndex(richTextBox1, text, num);
			}
			else
			{
				richTextBox1.AppendText(text);
			}
			richTextBox1.SelectionStart = richTextBox1.Text.Length;
		}

		private void GetRowColoumn(RichTextBox rtb, ref int _row, ref int _col)
		{
			int lineFromCharIndex = rtb.GetLineFromCharIndex(rtb.SelectionStart);
			rtb.GetCharIndexFromPosition(rtb.GetPositionFromCharIndex(rtb.SelectionStart));
			int index = rtb.SelectionStart - rtb.GetFirstCharIndexOfCurrentLine();
			Point point = new Point(lineFromCharIndex, index);
			point = rtb.GetPositionFromCharIndex(index);
			_row = lineFromCharIndex;
			_col = point.X;
		}

		private Point GetCaretCoordinates(RichTextBox rtb)
		{
			Point result = default(Point);
			result.X = rtb.GetLineFromCharIndex(rtb.SelectionStart);
			result.Y = rtb.SelectionStart - rtb.GetFirstCharIndexOfCurrentLine();
			return result;
		}

		private void AppendTextToIndex(RichTextBox rtb, string text, int index)
		{
			int selectionStart = rtb.SelectionStart + text.Length;
			rtb.Select(index, rtb.Text.Length - index);
			rtb.SelectedText = string.Empty;
			rtb.AppendText(text);
			rtb.SelectionStart = selectionStart;
		}

		private List<string> GetLine(string inputstring, out string laststring)
		{
			List<string> list = new List<string>();
			laststring = string.Empty;
			int num = 0;
			int num2 = 0;
			do
			{
				if (num + 1 < inputstring.Length)
				{
					num = inputstring.IndexOf(Environment.NewLine, num + 1);
					if (num != -1)
					{
						list.Add(inputstring.Substring(num2, num - num2).Trim());
						num2 = num;
					}
				}
				else
				{
					num = -1;
				}
			}
			while (num != -1);
			laststring = inputstring.Substring(num2, inputstring.Length - num2).Trim();
			return list;
		}

		private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
		{
			if (e.Modifiers == Keys.Control && e.KeyCode.ToString() == "V")
			{
				string text = Clipboard.GetText();
				string laststring = string.Empty;
				List<string> line = GetLine(text, out laststring);
				string text2 = richTextBox1.Text;
				if (!(text != text2) || line.Count != 0)
				{
					for (int i = 0; i < line.Count; i++)
					{
						if (i == 0 && line[i] != text2)
						{
							DisplayResponseWithNewLine(text2, rspTypedColor);
							RearrangeCommands(text2.Trim());
							ProcessCommand(text2);
						}
						else
						{
							DisplayResponseWithNewLine(line[i], rspTypedColor);
							RearrangeCommands(line[i].Trim());
							ProcessCommand(line[i]);
						}
					}
					richTextBox1.Clear();
					if (!string.IsNullOrEmpty(laststring))
					{
						richTextBox1.AppendText(laststring);
					}
				}
			}
			string empty = string.Empty;
			string empty2 = string.Empty;
			string empty3 = string.Empty;
			string empty4 = string.Empty;
			string empty5 = string.Empty;
			Convert.ToInt32(Keys.ControlKey | Keys.Control);
			GetInputString(richTextBox1, e);
			if (!e.Handled)
			{
				e.Handled = true;
				richTextBox1.Focus();
			}
		}

		private string GetInputString(RichTextBox tBox, KeyEventArgs e)
		{
			int selectionStart = tBox.SelectionStart;
			string typedChar = string.Empty;
			string[] array = new string[5];
			string empty = string.Empty;
			string empty2 = string.Empty;
			empty = tBox.Text;
			string empty3 = string.Empty;
			int num = -1;
			string empty5 = string.Empty;
			string response = string.Empty;
			string empty4 = string.Empty;
			if (selectionStart > 0 && e.KeyCode != Keys.ShiftKey && e.KeyCode != Keys.Alt && e.KeyCode != Keys.ControlKey && e.KeyValue != 37 && e.KeyData != Keys.Right && e.KeyCode != Keys.Up && e.KeyCode != Keys.Down && e.KeyCode != Keys.Tab && e.KeyCode != Keys.Return)
			{
				typedChar = tBox.Text.Substring(selectionStart - 1, 1);
				typedChar = tBox.Text.Substring(tBox.Text.Length - 1, 1);
				InputString = tBox.Text;
			}
			switch (e.KeyData)
			{
			case Keys.Space:
                _intellisesnectrl.ClearList();
                intellisesnepopup.Close();
                TypedChar = string.Empty;
				InputString = string.Empty;
				break;
			case Keys.Back:
			{
				int selectionStart2 = tBox.SelectionStart;
				try
				{
					if (selectionStart2 > 0)
					{
						typedChar = tBox.Text.Substring(selectionStart2 - 1, 1);
					}
				}
				catch (ArgumentOutOfRangeException)
				{
					typedChar = string.Empty;
					intellisesnepopup.Close();
				}
				if (TypedChar.Length > 0)
				{
					TypedChar = TypedChar.Substring(0, TypedChar.Length - 1);
				}
				InputString = tBox.Text;
				TypedChar = InputString;
				if (deletedChar.ToString().Equals(".") || string.IsNullOrEmpty(InputString))
				{
					_intellisesnectrl.ClearList();
					intellisesnepopup.Close();
				}
				break;
			}
			case Keys.Up:
			case Keys.Down:
				if (intellisesnepopup.Visible)
				{
					_intellisesnectrl.SetFocus(e);
					_intellisesnectrl.listBox1_KeyUp(this, e);
				}
				if (!e.Handled)
				{
					ParseStr(e.KeyValue);
					richTextBox1.SelectionStart = richTextBox1.TextLength;
				}
				break;
			case Keys.Decimal:
			case Keys.OemPeriod:
				_intellisesnectrl.CurrentCursorPos = richTextBox1.SelectionStart;
				_intellisesnectrl.TypedChar = typedChar;
				_intellisesnectrl.InputText = InputString;
				PopUpIntellisense(richTextBox1);
				break;
			case Keys.Escape:
				_intellisesnectrl.ClearList();
				intellisesnepopup.Close();
				break;
			case Keys.Tab:
			case Keys.Return:
			{
                string selectedText = _intellisesnectrl.GetSelectedText();
                if (!string.IsNullOrEmpty(selectedText))
                {
                    _intellisesnectrl_SelectedText(selectedText);
                    TypedChar = string.Empty;
                    e.Handled = true;
                    InputString = string.Empty;
                    intellisesnepopup.Close();
                    break;
                }
                        if (!tBox.Text.Contains(".") && tBox.Text.CompareTo(string.Empty) == 0)
				{
					tBox.Text = string.Empty;
				}
				else
				{
					empty = tBox.Text.TrimEnd();
					if (bLoginSuccess)
					{
						RearrangeCommands(empty.Trim());
						DisplayResponseWithNewLine(empty, rspTypedColor);
						empty2 = empty.ToLower();
						if (empty2.Contains("macrostation"))
						{
							if (empty2.Contains("macrostation") && empty2.Contains("close"))
							{
								bInMACROASCIIMode = false;
								ProcessCommand(empty);
								SetDisplayLabel();
							}
							else
							{
								bInMACROASCIIMode = true;
								ProcessCommand(empty);
								try
								{
									empty3 = empty.Substring(12);
									if (!string.IsNullOrEmpty(empty3))
									{
										num = Convert.ToInt32(empty3.Trim());
									}
								}
								catch (Exception ex)
								{
									string message = string.Format(macroStationExceptionFormat, ex.Message) + Environment.NewLine;
									SendLogMessage(message);
								}
								SetDisplayLabel(num);
							}
						}
						else if (empty2.Length > 5 && empty2.Substring(0, 6).Contains("reboot"))
						{
							DisplayResponseWithNewLine(sendingNotificationToStopCommunicationText, rspMessageColor);
							empty4 = "DISCONNECT";
							bLocalReboot = true;
							bResetInProgress = true;
							DisplayResponseWithNewLine(rebootingDeviceText, rspMessageColor);
							ProcessCommand(empty2);
							SendGlobalEvent(empty4);
						}
						else if (!empty2.Contains("macroslave") && empty2.Length > 2 && empty2.Substring(0, 3).Contains("$$$"))
						{
							DisplayResponseWithNewLine(resettingDeviceText, rspMessageColor);
							empty4 = "RESETACTIVE";
							bLocalReset = true;
							bResetInProgress = true;
							SendGlobalEvent(empty4);
							if ((!empty2.Contains("**")) ? AsyncGpasciiClient.PowerPMACReset(ResetType.Reset) : AsyncGpasciiClient.PowerPMACReset(ResetType.FullReset))
							{
								DisplayResponseWithNewLine(deviceResetCompleteText, rspMessageColor);
							}
							else
							{
								DisplayResponseWithNewLine(deviceResetFailedText, rspErrorColor);
							}
							SendGlobalEvent("RESETCOMPLETE");
							bLocalReset = false;
							bResetInProgress = false;
						}
						else if (empty2.Length > 2 && (empty2 == "save" || empty2 == "sav"))
						{
							PowerPmacSave(empty);
						}
						else if (bShowResponseTime)
						{
							ProcessSyncCommand(empty, out response);
						}
						else
						{
							ProcessCommand(empty);
						}
						richTextBox1.Text = string.Empty;
					}
					else
					{
						DisplayResponseWithNewLine(establishCommunicationToDeviceText, rspMessageColor);
					}
					tBox.Text = string.Empty;
					if (bResetInProgress && bLocalReboot)
					{
						DisplayResponseWithNewLine(resetInProgressText, rspMessageColor);
						richTextBox1.Clear();
						intellisesnepopup.Close();
						return string.Empty;
					}
				}
				TypedChar = string.Empty;
				e.Handled = true;
				InputString = string.Empty;
				intellisesnepopup.Close();
				break;
			}
			default:
			{
				int keyValue = e.KeyValue;
				TypedChar = InputString;
				_intellisesnectrl.CurrentCursorPos = richTextBox1.SelectionStart;
				_intellisesnectrl.TypedChar = typedChar;
				_intellisesnectrl.InputText = InputString;
				PopUpIntellisense(richTextBox1);
				break;
			}
			case Keys.ControlKey:
				break;
			}
			return empty;
		}

		private async void PowerPmacSave(string newCommand)
		{
			string response;
			ProcessSyncCommand("echo", out response);
			try
			{
				string[] array = response.Trim().Split(new char[1] { '\u0006' }, StringSplitOptions.RemoveEmptyEntries);
				lastEchoMode = Convert.ToInt32(array[0].Trim());
			}
			catch (Exception)
			{
				lastEchoMode = 0;
			}
			ProcessSyncCommand("echo0", out response);
			if (SyncGpasciiClient == null || !SyncGpasciiClient.GpAsciiConnected)
			{
				return;
			}
			ProcessSyncCommand("Sys.SyncSave", out response);
			bool usingSyncSave = response.StartsWith("Sys.SyncSave=1", true, CultureInfo.InvariantCulture);
			IWaitDialogService waitDialogService = ServiceManager.GetService<IWaitDialogService>();
			if (usingSyncSave)
			{
				waitDialogService.ShowDialog(productNameText, saveInProgresText, false);
			}
			try
			{
				Tuple<bool, string> tuple = await BackgroundSaveOnSyncClient(newCommand).ConfigureAwait(true);
				if (tuple.Item1)
				{
					DisplayResponseWithNewLine(tuple.Item2, rspNormalColor);
					SendGlobalEvent("SAVECOMPLETE");
				}
			}
			catch
			{
			}
			if (usingSyncSave)
			{
				waitDialogService.CloseDialog();
			}
			ProcessSyncCommand("echo" + lastEchoMode, out response);
		}

		private async Task<Tuple<bool, string>> BackgroundSaveOnSyncClient(string newCommand)
		{
			string response;
			return Tuple.Create(SyncGpasciiClient.PowerPMACSave(newCommand, out response), response);
		}

		private void PopUpIntellisense(RichTextBox rtb)
		{
			int _row = 0;
			int _col = 0;
			GetRowColoumn(rtb, ref _row, ref _col);
			if (_intellisesnectrl.ListBoxItemCount > 0)
			{
				intellisesnepopup.Show(richTextBox1, _col, richTextBox1.ClientRectangle);
			}
		}

		private void ParseStr(int KeyVal)
		{
			if (richTextBox1.Text == string.Empty)
			{
				cmdIndex = 0;
				richTextBox1.Text = CommandList[cmdIndex];
				return;
			}
			for (int i = 0; i < globalcmdcount; i++)
			{
				if (!(CommandList[i] == richTextBox1.Text.Trim()))
				{
					continue;
				}
				if (KeyVal == 38)
				{
					if (i < globalcmdcount - 1)
					{
						richTextBox1.Text = CommandList[++i];
					}
					else
					{
						richTextBox1.Text = CommandList[i];
					}
				}
				else if (i > 0)
				{
					richTextBox1.Text = CommandList[--i];
				}
				else
				{
					richTextBox1.Text = CommandList[i];
				}
				cmdIndex = i;
				break;
			}
		}

		public string GetHelpText()
		{
			string empty = string.Empty;
			try
			{
				string[] array = richTextBox1.Text.Trim().Split('.');
				string text2 = array[array.Length - 1];
				return HelpJumpKeywordService.GetHelpText(richTextBox1.Text.Trim());
			}
			catch (Exception ex)
			{
				SendLogMessage(ex.Message);
				return HelpJumpKeywordService.GetHelpText(richTextBox1.Text.Trim());
			}
		}

		private void cmdTextBox_TextChanged(object sender, EventArgs e)
		{
			if (this.displayTerminalTextChange != null)
			{
				TerminalTextArg e2 = new TerminalTextArg(richTextBox1.Text.Trim());
				this.displayTerminalTextChange(this, e2);
			}
		}

		protected override void Dispose(bool disposing)
		{
			try
			{
				if (disposing && components != null)
				{
					DisconnectDeviceCommunication();
					DatabaseReloadEventReceiverClass.StopMonitoring();
					DatabaseReloadEventReceiverClass.PPMACGlobalDatabaseSyncEvent -= DatabaseReloadEventReceiverClass_PPMACGlobalDatabaseSyncEvent;
					UserInterfaceData -= Control_UserInterfaceData;
                    if (intellisesnepopup != null)
                    {
                        intellisesnepopup.Dispose();
                    }
                    components.Dispose();
				}
				base.Dispose(disposing);
			}
			catch (ObjectDisposedException)
			{
			}
		}

		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
			this.propertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
			this.ambientToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
			this.controlToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
			this.setTerminalBufferToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
			this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
			this.clearBufferToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
			this.copyBufferToFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
			this.printBufferToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
			this.copyBufferToClipboardToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
			this.splitContainer1 = new System.Windows.Forms.SplitContainer();
			this.ResponseBox = new System.Windows.Forms.RichTextBox();
			this.richTextBox1 = new System.Windows.Forms.RichTextBox();
			this.contextMenuStrip1.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)this.splitContainer1).BeginInit();
			this.splitContainer1.Panel1.SuspendLayout();
			this.splitContainer1.Panel2.SuspendLayout();
			this.splitContainer1.SuspendLayout();
			base.SuspendLayout();
			this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[1] { this.propertiesToolStripMenuItem });
			this.contextMenuStrip1.Name = "contextMenuStrip1";
			this.contextMenuStrip1.Size = new System.Drawing.Size(128, 26);
			this.propertiesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[2] { this.ambientToolStripMenuItem, this.controlToolStripMenuItem });
			this.propertiesToolStripMenuItem.Name = "propertiesToolStripMenuItem";
			this.propertiesToolStripMenuItem.Size = new System.Drawing.Size(127, 22);
			this.propertiesToolStripMenuItem.Text = "&Properties";
			this.ambientToolStripMenuItem.Name = "ambientToolStripMenuItem";
			this.ambientToolStripMenuItem.Size = new System.Drawing.Size(120, 22);
			this.ambientToolStripMenuItem.Text = "&Ambient";
			this.ambientToolStripMenuItem.Click += new System.EventHandler(PPTerminalAmbientMenu_Click);
			this.controlToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[6] { this.setTerminalBufferToolStripMenuItem, this.toolStripSeparator1, this.clearBufferToolStripMenuItem, this.copyBufferToFileToolStripMenuItem, this.printBufferToolStripMenuItem, this.copyBufferToClipboardToolStripMenuItem });
			this.controlToolStripMenuItem.Name = "controlToolStripMenuItem";
			this.controlToolStripMenuItem.Size = new System.Drawing.Size(120, 22);
			this.controlToolStripMenuItem.Text = "&Control";
			this.setTerminalBufferToolStripMenuItem.Name = "setTerminalBufferToolStripMenuItem";
			this.setTerminalBufferToolStripMenuItem.Size = new System.Drawing.Size(206, 22);
			this.setTerminalBufferToolStripMenuItem.Text = "&General";
			this.setTerminalBufferToolStripMenuItem.Click += new System.EventHandler(setTerminalBufferToolStripMenuItem_Click);
			this.toolStripSeparator1.Name = "toolStripSeparator1";
			this.toolStripSeparator1.Size = new System.Drawing.Size(203, 6);
			this.clearBufferToolStripMenuItem.Name = "clearBufferToolStripMenuItem";
			this.clearBufferToolStripMenuItem.Size = new System.Drawing.Size(206, 22);
			this.clearBufferToolStripMenuItem.Text = "&Clear Buffer";
			this.clearBufferToolStripMenuItem.Click += new System.EventHandler(clearBufferToolStripMenuItem_Click);
			this.copyBufferToFileToolStripMenuItem.Name = "copyBufferToFileToolStripMenuItem";
			this.copyBufferToFileToolStripMenuItem.Size = new System.Drawing.Size(206, 22);
			this.copyBufferToFileToolStripMenuItem.Text = "&Save Buffer to File";
			this.copyBufferToFileToolStripMenuItem.Click += new System.EventHandler(copyBufferToFileToolStripMenuItem_Click);
			this.printBufferToolStripMenuItem.Name = "printBufferToolStripMenuItem";
			this.printBufferToolStripMenuItem.Size = new System.Drawing.Size(206, 22);
			this.printBufferToolStripMenuItem.Text = "&Print Buffer";
			this.printBufferToolStripMenuItem.Visible = false;
			this.printBufferToolStripMenuItem.Click += new System.EventHandler(printBufferToolStripMenuItem_Click);
			this.copyBufferToClipboardToolStripMenuItem.Name = "copyBufferToClipboardToolStripMenuItem";
			this.copyBufferToClipboardToolStripMenuItem.Size = new System.Drawing.Size(206, 22);
			this.copyBufferToClipboardToolStripMenuItem.Text = "Copy &Buffer to Clipboard";
			this.copyBufferToClipboardToolStripMenuItem.Click += new System.EventHandler(copyBufferToClipboardToolStripMenuItem_Click);
			this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
			this.splitContainer1.Location = new System.Drawing.Point(0, 0);
			this.splitContainer1.Margin = new System.Windows.Forms.Padding(5);
			this.splitContainer1.Name = "splitContainer1";
			this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
			this.splitContainer1.Panel1.Controls.Add(this.ResponseBox);
			this.splitContainer1.Panel2.Controls.Add(this.richTextBox1);
			this.splitContainer1.Size = new System.Drawing.Size(569, 569);
			this.splitContainer1.SplitterDistance = 540;
			this.splitContainer1.SplitterWidth = 2;
			this.splitContainer1.TabIndex = 8;
			this.ResponseBox.BackColor = System.Drawing.Color.Navy;
			this.ResponseBox.ContextMenuStrip = this.contextMenuStrip1;
			this.ResponseBox.Dock = System.Windows.Forms.DockStyle.Fill;
			this.ResponseBox.ForeColor = System.Drawing.Color.White;
			this.ResponseBox.Location = new System.Drawing.Point(0, 0);
			this.ResponseBox.Margin = new System.Windows.Forms.Padding(5);
			this.ResponseBox.Name = "ResponseBox";
			this.ResponseBox.ReadOnly = true;
			this.ResponseBox.Size = new System.Drawing.Size(569, 540);
			this.ResponseBox.TabIndex = 0;
			this.ResponseBox.TabStop = false;
			this.ResponseBox.Text = "N/A";
			this.ResponseBox.Click += new System.EventHandler(ResponseBox_Click);
			this.ResponseBox.KeyDown += new System.Windows.Forms.KeyEventHandler(ResponseBox_KeyDown);
			this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
			this.richTextBox1.Location = new System.Drawing.Point(0, 0);
			this.richTextBox1.Multiline = false;
			this.richTextBox1.Name = "richTextBox1";
			this.richTextBox1.Size = new System.Drawing.Size(569, 27);
			this.richTextBox1.TabIndex = 0;
			this.richTextBox1.Text = "";
			this.richTextBox1.TextChanged += new System.EventHandler(richTextBox1_TextChanged);
			this.richTextBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(richTextBox1_KeyDown);
			this.richTextBox1.KeyUp += new System.Windows.Forms.KeyEventHandler(richTextBox1_KeyUp);
			this.AllowDrop = true;
			base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
			base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			base.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
			this.BackColor = System.Drawing.SystemColors.Control;
			base.CausesValidation = false;
			this.ContextMenuStrip = this.contextMenuStrip1;
			base.Controls.Add(this.splitContainer1);
			this.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);
			this.ForeColor = System.Drawing.SystemColors.ControlText;
			base.Margin = new System.Windows.Forms.Padding(5);
			base.Name = "PPTerminalControl";
			base.Size = new System.Drawing.Size(569, 569);
			base.Load += new System.EventHandler(PPTerminalControl_Load);
			base.BackColorChanged += new System.EventHandler(PPTerminalControl_BackColorChanged);
			base.FontChanged += new System.EventHandler(PPTerminalControl_FontChanged);
			base.ForeColorChanged += new System.EventHandler(PPTerminalControl_ForeColorChanged);
			base.Click += new System.EventHandler(PPTerminalControl_Click);
			base.MouseClick += new System.Windows.Forms.MouseEventHandler(PPTerminalControl_MouseClick);
			this.contextMenuStrip1.ResumeLayout(false);
			this.splitContainer1.Panel1.ResumeLayout(false);
			this.splitContainer1.Panel2.ResumeLayout(false);
			((System.ComponentModel.ISupportInitialize)this.splitContainer1).EndInit();
			this.splitContainer1.ResumeLayout(false);
			base.ResumeLayout(false);
		}
	}
}
